-module(player).
-behaviour(gen_server).
-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
    code_change/3, del_mail/2, collect_mail/2, send_mail/2, get_reward/2, stop/1]).
-define(SERVER, ?MODULE).
-include("info.hrl").


start_link(Account) ->
    gen_server:start_link({local, list_to_atom(Account)}, ?MODULE, Account, []).

feedback(X) ->
    X.

init(Account) ->
    Player = dets:lookup(players, Account),
    %%   其他系统在该玩家上线时要发给该玩家的邮件由其他系统调用 send_mail 完成
    %% 清理过期邮件
    XPlayer = lib_mail:clean_over_mail(Player),
    feedback(XPlayer),  %%   向前端一次性发送该玩家所有的信息，
    {ok, Player}.

get_reward(Account, MailId) ->
    gen_server:cast(list_to_atom(Account), {get_reward, MailId}).

del_mail(Account, MailId) ->
    gen_server:cast(list_to_atom(Account), {del_mail, MailId}).

collect_mail(Account, MailId) ->
    gen_server:cast(list_to_atom(Account), {collect_mail, MailId}).

%% 邮件内容由发邮件的那个进程给出，邮件系统并不需要给出具体的邮件内容
send_mail(Account, Mail) ->
    gen_server:cast(list_to_atom(Account), {send_mail, Mail}).

stop(Account) ->
    gen_server:cast(list_to_atom(Account), stop).


handle_cast({get_reward, MailId}, State) ->
    {noreply, lib_mail:get_reward(MailId, State)};

handle_cast({del_mail, MailId}, State) ->
    {noreply, lib_mail:del_mail(MailId, State)};

handle_cast({collect_mail, MailId}, State) ->
    {noreply, lib_mail:collect_mail(MailId, State)};

handle_cast({send_mail, Mail}, State) ->
    {noreply, lib_mail:send_mail(Mail, State)};


handle_cast(stop, State) ->   %% 结束时持久化入dets
    dets:insert(players, State),
    {stop, normal, State}.

handle_call(_Request, _From, State) ->
    {reply, ok, State}.

handle_info(_Info, State) ->
    {noreply, State}.
terminate(_Reason, _State) ->
    ok.
code_change(_OldVsn, State, _Extra) ->
    {ok, State}.


